package com.nchu.learn.netty.handler;

import com.nchu.learn.netty.model.Message;
import com.nchu.learn.netty.resolver.*;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author fujianjian
 * @project self-learning
 * @date 2020/1/16 13:50
 */
@Slf4j
public class ServerMessageHandler extends SimpleChannelInboundHandler<Message> {

    private MessageResolverFactory resolverFactory = MessageResolverFactory.getInstance();

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Message message) throws Exception {
        Resolver resolver = resolverFactory.getResolver(message);
        Message result = resolver.resolve(message);
        channelHandlerContext.writeAndFlush(result);
    }


    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        resolverFactory.registerResolver(new RequestMessageResolver());
        resolverFactory.registerResolver(new ResponseMessageResolver());
        resolverFactory.registerResolver(new PingMessageResolver());
        resolverFactory.registerResolver(new PongMessageResolver());
    }
}
